package com.cms.web;

import java.io.IOException;
import java.util.HashMap;
import java.util.Locale;
import java.util.ResourceBundle;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;

import com.cms.facade.RequestFacade;
import com.cms.facade.SessionFacade;
import com.cms.framework.Command;
import com.cms.framework.CommandException;
import com.cms.framework.CommandToken;
import com.cms.util.FileHelper;
import com.cms.util.Formater;
import com.cms.util.StringHelper;
import com.cms.config.LocaleDef;

public class ActionServlet extends HttpServlet {
	private final static Logger logger = Logger.getLogger(ActionServlet.class);

	private static HashMap<String,Command> commands;
	private String error = "/error.jsp";

	public void init(ServletConfig config) throws ServletException {
		super.init(config);
		ResourceBundle rb = ResourceBundle.getBundle("config",Locale.getDefault());
		FileHelper.initPathDIR(rb.getString("FILE_PATH_BASE"));
		initCommandMaps();
		
		//ResourceBundle rb = ResourceBundle.getBundle("trivial",Locale.getDefault());
	}

	public void service(HttpServletRequest req, HttpServletResponse res)
			throws ServletException, IOException {
		res.addHeader("P3P", "CP=CAO PSA OUR");
		String next = "/index.jsp";
		Command command = null;
		HttpSession session = req.getSession(false);
		try {

			String cmdString = req.getParameter("cmd");
			String doNothing = req.getParameter("doNothing");
			String trivallog = Formater.getParam(req.getParameter("trivallog"),
					"0");

			if (!StringHelper.isEmpty(doNothing) && doNothing.equals("Y")) {
				if ((session == null) && !trivallog.equals("1")) {
					cmdString = "index";
				} else {
					next = req.getParameter("nextPage");
					String preCmd = req.getParameter("preCmd");
					if (!StringHelper.isEmpty(preCmd)) {
						command = lookupCommand(preCmd);
						command.execute(req);
					}
				}
			} else {

				cmdString = req.getParameter("cmd");

				if (StringHelper.isEmpty(cmdString)) {
					cmdString = "index";
				}

				if (!cmdString.equals("index")) {

					if (session == null) {
						cmdString = "index";
					}
				}

				RequestFacade.setSuccessFlag(req, Boolean.TRUE);

				String preCmd = req.getParameter("preCmd");
				if (!StringHelper.isEmpty(preCmd)) {
					logger.debug("the preCmd is:" + preCmd);
					command = lookupCommand(preCmd);
					command.execute(req);
				}

				logger.debug("the cmd is:" + cmdString);
				command = lookupCommand(cmdString);
				next = command.execute(req);

				String nextCmd = req.getParameter("nextCmd");
				if (!StringHelper.isEmpty(nextCmd)) {
					logger.debug("the nextCmd is:" + nextCmd);
					command = lookupCommand(nextCmd);
					next = command.execute(req);
				}

				String finallyCmd = req.getParameter("finallyCmd");
				if (finallyCmd != null && !finallyCmd.equals("")) {
					logger.debug("the finallyCmd is:" + finallyCmd);
					command = lookupCommand(finallyCmd);
					next = command.execute(req);
				}

				logger.debug("after final:" + cmdString + ", page: " + next);

			}

			String setTokenFlag = req.getParameter("set_token_flag");
			if (setTokenFlag == null || setTokenFlag.equals("Y")) {
				CommandToken.set(req);
			}


			
		} catch (CommandException e) {
			e.printStackTrace();
			req.setAttribute("javax.servlet.jsp.jspException", e.getMessage());
			next = error;
		} finally {
			System.out.println("next page:" + next);
			RequestDispatcher rd;
			rd = getServletContext().getRequestDispatcher(next);
			rd.forward(req, res);
		}
	}

	public static Command lookupCommand(String cmd) throws CommandException {
		if (commands.containsKey(cmd)) {
			System.out.println(((Command) commands.get(cmd)).getClass()
					.getName());
			return (Command) commands.get(cmd);
		} else {
			System.out.println("invalid command:" + cmd);
			throw new CommandException("Invalid Command Identifier");
		}
	}

	private void initCommandMaps() {
		commands = new HashMap();
		commands.put("index", new com.cms.framework.DoNothingCommand("/index.jsp"));
		// commands.put("getphotolist", new
		// com.cms.photo.GetPhotoListCommand("/jsp/photoList.jsp"));
	}
}
